package com.james.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.james.constant.GatewayConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @ClassName: RouteConfig
 * @Author: JamesWang
 * @Date: 2021/4/21 20:48
 * @Description: 代码路由的方式 目的是拿到登录的响应值 存入redis
 * @Version:1.0
 */
@Configuration
public class RouteConfig {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 路由存放token
     * @param builder
     * @return
     */
//    @Bean
//    public RouteLocator routeLocator(RouteLocatorBuilder builder) {
//        RouteLocatorBuilder.Builder routes = builder.routes();
//        routes.route("oauth-server-router", r -> r.path("/oauth/token")
//                .filters(f -> f.modifyResponseBody(String.class, String.class,
//                        (exchanges, s) -> {
//                            // 拿到登录响应值 s
//                            JSONObject jsonObject = JSONUtil.parseObj(s);
//                            String accessToken = jsonObject.getStr("access_token");
//                            if (StringUtils.hasText(accessToken)) {
//                                // 登录成功了
//                                // 拿到过期时间
//                                Long expiresIn = jsonObject.getLong("expires_in");
//                                // 存入redis
//                                redisTemplate.opsForValue().set(GatewayConstant.TOKEN_JWT_PREFIX + accessToken, "", Duration.ofSeconds(expiresIn));
//                            }
//                            return Mono.just(s);
//                        }))
//                .uri("lb://auth-server"));
//        return routes.build();
//    }

}
